package me.zhengjie.util;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Component
public class FTPUtil {
    /**
     *  获取FTP服务器中中指定文件
     * @param server ip
     * @param port 端口
     * @param username 账号
     * @param password 密码
     * @param remoteFilePath 指定文件名称
     */
    public static InputStream downloadFile(String server, int port, String username, String password, String remoteFilePath) {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(server, port);
            ftpClient.login(username, password);

            // 设置被动模式
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            return ftpClient.retrieveFileStream(remoteFilePath);

            // 获取指定名称的文件
            /*boolean success = ftpClient.retrieveFile(remoteFilePath, outputStream);

            if (success) {
                *//*byte[] fileContent = outputStream.toByteArray();
                return java.util.Base64.getEncoder().encodeToString(fileContent);*//*
                return outputStream;
            } else {
                 return null;
                *//*return "Error: unable to retrieve the file from FTP"*//*
            }*/

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
